﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Kokomo
{
	public static class PathHelper
	{
		public static string FindDll(string moduleName, string sourceModulePath)
		{
			ArgumentValidation.CheckNullArgument("moduleName", moduleName);

			string sourceModuleDirectory = Path.GetDirectoryName(sourceModulePath);

			// Local directory
			var searchDirectories = new string[] {
				sourceModuleDirectory,
				Environment.SystemDirectory,
				Environment.GetFolderPath( Environment.SpecialFolder.Windows),
				Environment.CurrentDirectory,
			}.Concat(
				Environment.GetEnvironmentVariable("PATH").Split(';')
			);

			foreach (var searchDirectory in searchDirectories)
			{
				string modulePath = Path.Combine(searchDirectory, moduleName);
				if (File.Exists(modulePath))
				{
					return modulePath;
				}
			}

			return null;
		}
		public static string MakeRelativePath(string path, string basePath)
		{
			ArgumentValidation.CheckNullArgument("path", path);
			ArgumentValidation.CheckNullArgument("basePath", basePath);

			string[] pathParts = path.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
			string[] basePathParts = basePath.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);

			int minParts = Math.Min(pathParts.Length, basePathParts.Length);

			int escapeCount = Math.Max(basePathParts.Length - minParts, 0);
			int commonPartCount = 0;
			for (commonPartCount = 0; (commonPartCount < minParts) && (pathParts[commonPartCount] == basePathParts[commonPartCount]); commonPartCount++) ;

			escapeCount += (basePathParts.Length - commonPartCount);

			StringBuilder pathBuilder = new StringBuilder();
			for (int i = 0; i < escapeCount; i++)
			{
				if (pathBuilder.Length > 0)
				{
					pathBuilder.Append(@"\");
				}
				pathBuilder.Append("..");
			}
			for (int i = commonPartCount; i < pathParts.Length; i++)
			{
				if (pathBuilder.Length > 0)
				{
					pathBuilder.Append(@"\");
				}
				pathBuilder.Append(pathParts[i]);
			}

			return pathBuilder.ToString();
		}
	}
}
